<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Lifecycle;

use SplObjectStorage;
use Slipstream\Lifecycle\Adapter\AdapterInterface;

/**
 *
 *
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class ShutdownRegistry implements Startable
{
	/**
	 * @var AdapterInterface
	 */
	protected $adapter;
	
	/**
	 * @var SplObjectStorage<object>
	 */
	protected $instances;
	
	/**
	 * Class constructor
	 *
	 * @param AdapterInterface $adapter
	 * @return void
	 */
	public function __construct(AdapterInterface $adapter)
	{
		$this->adapter = $adapter;
		$this->instances = new SplObjectStorage();
	}
	
	/**
	 * Registers an instance with the container to be shut down at the
	 * end of its lifecycle
	 *
	 * @param unknown_type $instance
	 * @return void
	 */
	public function registerInstance($instance)
	{
		$this->instances->attach($instance);
	}
	
	/**
	 * Unregister an instance from the container
	 *
	 * @param unknown_type $instance
	 * @return void
	 */
	public function unregisterInstance($instance)
	{
		$this->instances->detach($instance);
	}
	
	/**
	 * Returns the instances registered with the container
	 * @return SplObjectStorage<object>
	 */
	public function getInstances()
	{
		return $this->instances;
	}
	
	/**
	 * Initializes the component
	 * @return void
	 */
	public function initialize()
	{
	}
	
	/**
	 * Shuts down the component
	 * @return void
	 */
	public function shutdown()
	{
		foreach($this->instances as $instance) {
			$this->adapter->shutdown($instance);
		}
	}
}